package zk_01.zookeeper;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

public class Master implements Watcher{
	private ZooKeeper zk;
	private String hostPort;
	
	public Master(String hostPort) {
		this.hostPort=hostPort;
	}
	
	void startZK() throws ZKConnectIOException{
		try {
			zk = new ZooKeeper(hostPort,15000,this);
		} catch (IOException e) {
			//为了更好的区分异常类型，可以自定义异常类型，并做正确的日志输出，方便以后定位问题
			throw new ZKConnectIOException();
		}
	}
	
	void stopZK() throws InterruptedException{
		//愿意的朋友都可以自定义异常哈
		zk.close();
	}
	
	public static void main(String[] args) {
	    Master m = new Master("192.168.1.113:2181");
		try {
			m.startZK();
			m.createMaster();
			Thread.sleep(60000);
			m.stopZK();
		} catch (ZKConnectIOException e) {
			//根据自己的需求做异常处理，比如重新发起连接
		} catch (InterruptedException e) {
			//可以细化InterruptedException，分别做应对处理，朋友们发挥自己的脑力吧
			e.printStackTrace();
		}
	}
	
	public void createMaster(){
		try {
			/*
			 * 入参：
			 * 1.znode完整路径
			 * 2.znode需要保留的数据（都是byte[]）
			 * 3.ACL模式，这里选择的OPEN_ACL_UNSAFE
			 * 4.节点类型，这里选择的非有序临时节点（表示服务器知道客户端已经失去联系，则会自动删除它创建的所有临时节点）
			 */
			zk.create("/master", "myData".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
		} catch (KeeperException e) {
			//个人建议提取KeeperException中的Code，做针对性的异常跑出，精准定位
		} catch (InterruptedException e) {
			//自己看着办吧，我就是这么不负责任
			e.printStackTrace();
		}
	}
	
	public void process(WatchedEvent e) {
		System.out.println(e);
	}
}

class ZKConnectIOException extends Exception{
	public ZKConnectIOException() {
	}
	public ZKConnectIOException(String msg) {
		super(msg);
	}
}
